from flask import render_template, current_app, session, request, jsonify, g

from info import constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blue


@index_blue.route("/news_list")
def news_list():
    """
    获取首页新闻数据
    :return:
    """
    # 1. 获取参数
    cid = request.args.get("cid", '1')
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")
    # 校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 2. 去数据库查询数据
    filters = [News.status == 0]  # 添加过滤条件,只显示审核通过的新闻

    if cid != 1:  # 查询的不是最新的数据
        # 需要添加条件
        filters.append(News.category_id == cid)
    # 查询数据
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    # 取到当前页的数据
    new_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page
    # 将模型对象列表转为列表字典
    news_list_li = []
    for news in new_list:
        news_list_li.append(news.to_basic_dict())
    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_list_li": news_list_li
    }
    # 3. 返回数据
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@index_blue.route("/")
@user_login_data
def index():
    """
    显示首页
    :return:
    """

    # 显示用户是否登录的逻辑
    user = g.user

    # 显示右侧数据的逻辑
    # 1. 去数据库查询数据
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    # 字典列表
    news_list_li = []
    # 遍历模型对象,将模型对象转换为字典添加到字典列表中
    for news in news_list:
        news_list_li.append(news.to_basic_dict())

    # 查询分类数据, 通过模板的形式渲染
    categories = Category.query.all()
    category_li = []
    for category in categories:
        category_li.append(category.to_dict())

    data = {
        "user": user.to_dict() if user else None,
        "news_list_li": news_list_li,
        "category_li": category_li
    }

    return render_template("news/index.html", data=data)


# 加载favicon图标
@index_blue.route("/favicon.ico")
def favicon():
    return current_app.send_static_file("news/favicon.ico")
